package com.example.smartcity.ui.person.login

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.smartcity.R
import com.example.smartcity.databinding.ActivityInfoBinding
import com.example.smartcity.logic.net_work.Response
import com.example.smartcity.logic.utils.BaseActivity
import com.example.smartcity.logic.utils.Toast.Companion.showToast
import com.example.smartcity.ui.person.PersonViewModel
import kotlinx.coroutines.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import org.json.JSONObject

class infoActivity : BaseActivity() {

    private val viewModel by lazy {
        ViewModelProvider(this)[PersonViewModel::class.java]
    }

    private lateinit var mBinding: ActivityInfoBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityInfoBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        title = "个人信息"
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        // 显示用户信息
        initShow()

        // 修改用户信息
        initModification()
    }

    /**
     * 修改用户信息
     */
    @OptIn(DelicateCoroutinesApi::class)
    private fun initModification() {
        mBinding.isOK.setOnClickListener {
            // 设置数据
            val j = JSONObject().apply {
                put("nickName", mBinding.nickName.text.toString())
                if(mBinding.sex.text.toString() == "男") put("sex", 0)
                else if (mBinding.sex.text.toString() == "女") put("sex", 1)
                put("email", mBinding.email.text.toString())
                put("phonenumber", mBinding.phonenumber.text.toString())
                put("idCard", mBinding.idCard.text.toString())
            }

            // 获取token
            getSharedPreferences("token", Context.MODE_PRIVATE).apply {
                // 获取token
                val t = this.getString("token", "")
                GlobalScope.launch {
                    // 发起网络请求
                    val ok = Response.getModification(t.toString(), RequestBody.create("application/json".toMediaType(), j.toString()))
                    runOnUiThread {
                        AlertDialog.Builder(this@infoActivity).apply {
                            setTitle("提示")
                            setMessage("确定要修改数据吗?")
                            setPositiveButton("确定"){_, _ ->
                                if (ok.code == 200){
                                    "修改成功！".showToast()
                                } else ok.msg.showToast()
                            }
                            setNegativeButton("取消"){ _, _ ->

                            }
                            show()
                        }

                    }
                }
            }
        }
    }

    /**
     * 显示用户信息
     */
    private fun initShow() {
        getSharedPreferences("token", Context.MODE_PRIVATE).apply {
            viewModel.setLogin(this.getString("token", "").toString())
            viewModel.loginDataLive.observe(this@infoActivity, Observer { resources ->
                val body = resources.getOrNull()
                if(body != null){
                    mBinding.userId.text = "ID: ${body.userId}"
                    mBinding.balance.text = "余额: ${body.balance}$"
                    mBinding.score.text = "积分: ${body.score}"

                    mBinding.nickName.setText(body.nickName)
                    if(body.sex == "0") mBinding.sex.setText("男")
                    else if (body.sex == "1") mBinding.sex.setText("女")
                    mBinding.email.setText(body.email)
                    mBinding.phonenumber.setText(body.phonenumber)
                    mBinding.idCard.setText(body.idCard)
                }
            })
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // 销毁意图
        this.finish()
        return super.onOptionsItemSelected(item)
    }
}